<html>
<head>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Cabin">
<style>
body {
  min-width:570px;
  overflow-x:hidden;
  font-family: 'Cabin', arial, serif;
  font-size:13 px;
}

h1
{
	font-size: 14px;
	font-weight: bold;
	color: navy;
	background-color: lime;
}

img {
  margin:5px;
  border:2px solid black;
  vertical-align:middle;
  width:75px;
  height:75px;
}

table
{
	border: 1px solid green;
	border-collapse: collapse;
	font-size:12px;
	table-layout:fixed;
}

table th
{
	background-color: lime;
	border: 1px solid green;
}


table td
{
	border: 1px solid green;
}
</style>

<script src="https://www.google.com/jsapi"></script>
<script src="jquery-1.4.3.min.js"></script>

</head>

<body>
<h1>Instalytics</h1>
	<button id="authButton">Loading...</button>
<div id="dataControls" style="display:none">
  <p>
    For this user, retrieve the first 50 accounts with profile ID and table ID
    <button id="getAccount">Get Account Data</button>
  </p>
  <div id="outputDiv"></div>
  <p>
    For this profile, show top 10 pageviews in descending order:
    <input type="text" id="tableId" value="ga:3149038"/> (insert Table ID)
	<br />
    Start Date:  <input type="text" id="startDate" value="2011-01-01"/>
	<br />
    End Date:  <input type="text" id="endDate" value="2011-02-18"/>
	
    <button id="getData">Get Report Data</button>
  </p>
</div>

<hr />
<div id="pageLevelDataDiv"></div>
<hr />
<div id="referrerDiv"></div>

<script>
	
	// Load the Google data JavaScript client library
	google.load('gdata', '2.x', {packages: ['analytics']});

	// Set the callback function when the library is ready
	google.setOnLoadCallback(init);
	
	var tableIdToQuery;
	var queryStartDate;
	var queryEndDate;
	
	
		var myService;
		var scope = 'https://www.google.com/analytics/feeds/';

		function init() {
		  myService = new google.gdata.analytics.AnalyticsService('gaExportAPI_acctSample_v2.0');
			scope = 'https://www.google.com/analytics/feeds';
			var button = document.getElementById('authButton');

			// Add a click handler to the authorize button.
			button.onclick = function() {
			  // Test if the user is not authorized
				  if (!bgPage.oauth.hasToken()) {
					// Authorize the user.
					google.accounts.user.login(scope);
				  } else {
					// Log the user out.
					google.accounts.user.logout();
					getStatus();
				  }
			}
		getStatus();
		}    

		function getStatus() {
			var getAccountButton = document.getElementById('getAccount');
			getAccountButton.onclick = getAccountFeed;

			var getDataButton = document.getElementById('getData');
			getDataButton.onclick = getDataFeed;

			var dataControls = document.getElementById('dataControls');
			var loginButton = document.getElementById('authButton');
			if (!bgPage.oauth.hasToken()) {
			  dataControls.style.display = 'none';   // hide control div
			  loginButton.innerHTML = 'Access Google Analytics';
			} else {
			  dataControls.style.display = 'block';  // show control div
			  loginButton.innerHTML = 'Logout';
			}
		}  
	
	var bgPage = chrome.extension.getBackgroundPage();
	
		function getAccountFeed() {
		  var myFeedUri =
			  'https://www.google.com/analytics/feeds/accounts/default';
		  /*myService.getAccountFeed(myFeedUri, handleAccountFeed, handleError);*/
		  
		  //var url = 'https://docs.google.com/feeds/default/private/full';
		  var request = {
			'method': 'GET',
			'parameters': {'alt': 'json'}
		  };

		  // Send: GET https://docs.google.com/feeds/default/private/full?alt=json
		  bgPage.oauth.sendSignedRequest(myFeedUri, handleAccountFeed, request);
		}
		
	function handleAccountFeed(rawResult) {
		var result = jQuery.parseJSON(rawResult);
		console.log(result);
	
		  // An array of analytics feed entries.
		  var entries = result.feed.entry;

		  // Create an HTML Table using an array of elements.
		  var outputTable = ['<table><tr>',
							 '<th>Account Name</th>',
							 '<th>Profile Name</th>',
							 '<th>Profile ID</th>',
							 '<th>Table Id</th></tr>'];

		  // Iterate through the feed entries and add the data as table rows.
		  for (var i = 0, entry; entry = entries[i]; ++i) {

			// Add a row in the HTML Table array for each value.
			/*var row = [
			  entry.getPropertyValue('ga:AccountName'),
			  entry.getTitle().getText(),
			  entry.getPropertyValue('ga:ProfileId'),
			  entry.getTableId().getValue()
			].join('</td><td>');*/
			
			var row = new Array();
			var accountName, title, profileName, tableId="";
			jQuery.each(entry.dxp$property, function(key, val){
													if(val.name == "ga:accountName"){
														accountName = val.value;
													}else if(val.name== "ga:profileId"){
														profileId = val.value;
													}
													});
			
			tableId = entry.dxp$tableId.$t;
			profileName = entry.title.$t;
			
			row.push(accountName);
			row.push(profileName);
			row.push(profileId);
			row.push(tableId);
			
			
			outputTable.push('<tr><td>', row.join('</td><td>'), '</td></tr>');
		  }
		  outputTable.push('</table>');

		  // Insert the table into the UI.
		  document.getElementById('outputDiv').innerHTML =
			  outputTable.join('');
		}
		
	function getDataFeed() {
	//	document.getElementById('outputDiv').innerHTML = "";
		document.getElementById('referrerDiv').innerHTML = "";
		document.getElementById('pageLevelDataDiv').innerHTML = "";
		
		tableIdToQuery = document.getElementById("tableId").value;
		
		queryStartDate = document.getElementById("startDate").value;
	    queryEndDate = document.getElementById("endDate").value;;

		
		if (!tableIdToQuery) {
			alert("TableID is required. Please enter one and retry.");
			return;
		}
		
		
	var myFeedUri = 'https://www.google.com/analytics/feeds/data';// +
		/*'?start-date=2011-01-01' +
		'&end-date=2011-02-18' +
		'&dimensions=ga:pageTitle,ga:pagePath' +
		'&metrics=ga:pageviews' +
		'&sort=-ga:pageviews' +
		'&max-results=10' +
		'&ids=ga:3149038' ; */ //+ document.getElementById('tableId').value;

		  
		  		var request = {
			'method': 'GET',
			'parameters' :{
			'start-date' : queryStartDate,
			'end-date' : queryEndDate,
			'dimensions' : 'ga:pageTitle,ga:pagePath',
			'metrics' : 'ga:uniquePageviews,ga:avgTimeOnPage',
			'sort'	  : '-ga:uniquePageviews',
			'max-results' : '10',
			'ids' :  tableIdToQuery,
			'alt' : 'json'}			
		  };

		  
		//var analyticsService = new google.gdata.analytics.AnalyticsService('iSample_dataVisits_v1.0');
		//analyticsService.getDataFeed(myFeedUri, handleDataFeed, handleError);
		  // Send: GET https://docs.google.com/feeds/default/private/full?alt=json
		  bgPage.oauth.sendSignedRequest(myFeedUri, handleDataFeed, request);
		  
	}
		
	function handleError(e) {
    var error = 'There was an error!\n';
    if (e.cause) {
      error += e.cause.status;
    } else {
      error.message;
    }
    alert(error);
	}
	
	
	function handleReferrerDataFeed(rawResult)
	{
		
		console.log("Received result");
		var result = jQuery.parseJSON(rawResult);
		console.log(result);
		var entries = result.feed.entry;
		// Create an HTML Table using an array of elements.
		  var outputTable = ['<table><tr>',
							 '<th>Site</th>',
							 '<th>Path</th></tr>'];

		  // Iterate through the feed entries and add the data as table rows.
		  for (var i = 0, entry; entry = entries[i]; ++i) {

			// Add a row in the HTML Table array for each value.
			/*var row = [
			  entry.getPropertyValue('ga:AccountName'),
			  entry.getTitle().getText(),
			  entry.getPropertyValue('ga:ProfileId'),
			  entry.getTableId().getValue()
			].join('</td><td>');*/
			
			if(entry.dxp$dimension[0].value == "(direct)")
					continue;
			
			var row = new Array();
			var site, path ="";
			
			jQuery.each(entry.dxp$dimension, function(key, val){
													if(val.name == "ga:source"){
														site = val.value;
													}else if(val.name== "ga:referralPath"){
														path = val.value;
													}
													});
			
			
			row.push(site);
			row.push(path);
			
			
			outputTable.push('<tr><td>', row.join('</td><td>'), '</td></tr>');
			
		  }
		  outputTable.push('</table>');
		   // Insert the table into the UI.
		  document.getElementById('referrerDiv').innerHTML =
			  outputTable.join('');
		  
		  //console.log(outputTable);
		  
	}

	function handleDataFeed(rawResult) {
	//console.log(rawResult);
	//var result = jQuery.parseXML(rawResult);
	
	var result = jQuery.parseJSON(rawResult);
	console.log(result);
	
	 // Create an HTML Table using an array of elements.
 	var outputTable;

	if (result.feed.entry && result.feed.entry.length > 0) 
	{
	
	 // Create an HTML Table using an array of elements.
	 outputTable = ['<table><tr>',
	                    '<th>Page Title</th>',
	                    '<th>Page Path</th>',
	                    '<th>Pageviews</th>',
						'<th>Avg Time on Page (sec)</th>',
						'</tr>'];
			
	 // An array of Analytics feed entries.
	 var entries = result.feed.entry;
	 for (var i=0; i<entries.length; i++)
	 {
	     // Add a row in the HTML Table array.
	     var row = [
	
		   //Page Title
	       entries[i].dxp$dimension[0].value,
	
		   //Page Path
	       entries[i].dxp$dimension[1].value,
		   
		   //Unique Page Views
	       entries[i].dxp$metric[0].value,
		   
		   //Avg. Time on Page
	       parseInt(entries[i].dxp$metric[1].value) 
		   	   
	     ].join('</td><td>'); 	
		 
	      outputTable.push('<tr><td>', row, '</td></tr>');
	 }	
	   outputTable.push('</table>');
	
	}
	else
	{
		outputTable = "No Page Level Analytics Data Found";	
	}

	//Display Page Level Data
  	document.getElementById('pageLevelDataDiv').innerHTML = outputTable.join('');
			
	
	
	 var myBgPage = chrome.extension.getBackgroundPage();
	 var myFeedUri = 'https://www.google.com/analytics/feeds/data';
	
	 console.log("About to send second request");
	  var referrerRequest = {
		  'method': 'GET',
		'parameters' :{
		'start-date' : queryStartDate,
		'end-date' : queryEndDate,
		'dimensions' : 'ga:source,ga:referralPath',
		'metrics' : 'ga:pageviews',
		'ids' : tableIdToQuery,
		'alt' : 'json'
		}
	  };
	  
	  
	  myBgPage.oauth.sendSignedRequest(myFeedUri, handleReferrerDataFeed, referrerRequest);
	 

 /*
 // An array of Analytics feed entries.
 var entries = result.feed.getEntries();
 
 // Create an HTML Table using an array of elements.
 var outputTable = ['<table><tr>',
                    '<th>Page Title</th>',
                    '<th>Page Path</th>',
                    '<th>Pageviews</th></tr>'];

  // Iterate through the feed entries and add the data as table rows.
  for (var i = 0, entry; entry = entries[i]; ++i) {

     // Add a row in the HTML Table array.
     var row = [
       entry.getValueOf('ga:pageTitle'),
       entry.getValueOf('ga:pagePath'),
       entry.getValueOf('ga:pageviews')
     ].join('</td><td>');
     outputTable.push('<tr><td>', row, '</td></tr>');
   }
   outputTable.push('</table>');

  // Insert the table into the UI.
  document.getElementById('outputDiv').innerHTML =
      outputTable.join(''); */
	  
	console.log(bgPage.window);
}

	
</script>
</body>
</html>